import React, { useState } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Grid,
  Card,
  CardContent,
  Divider,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  Stack,
  Snackbar,
  useTheme,
  alpha,
  Fade,
  Paper,
  Chip,
  FormControl,
  FormControlLabel,
  FormLabel,
  Radio,
  RadioGroup,
  InputLabel,
  Select,
  MenuItem,
  Tab,
  Tabs,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import WorkIcon from '@mui/icons-material/Work';
import BusinessCenterIcon from '@mui/icons-material/BusinessCenter';
import BusinessIcon from '@mui/icons-material/Business';
import DateRangeIcon from '@mui/icons-material/DateRange';
import ArrowRightAltIcon from '@mui/icons-material/ArrowRightAlt';

interface WorkExp {
  id: number;
  company: string;
  position: string;
  start_date: string;
  end_date: string | null;
  description: string;
  user_id: number;
}

interface InternshipExp {
  id: number;
  company: string;
  position: string;
  period: string;
  description?: string;
}

// 通用经历类型，统一工作和实习数据结构
interface Experience {
  id: number;
  type: 'work' | 'internship'; // 区分工作或实习
  company: string;
  position: string;
  startDate: string; // 对于工作经历是日期，对于实习是period的开始
  endDate?: string; // 可能是日期或结束描述
  description?: string;
  originalData: WorkExp | InternshipExp; // 保存原始数据用于编辑
}

interface WorkInternExperienceProps {
  workExperiences: WorkExp[];
  internships: InternshipExp[];
  onUpdate: () => void;
}

const formatDate = (dateString: string | null) => {
  if (!dateString) return '至今';
  
  // 假设日期格式为 YYYY-MM-DD
  const parts = dateString.split('-');
  if (parts.length >= 2) {
    return `${parts[0]}年${parts[1]}月`;
  }
  return dateString;
};

const WorkInternExperience: React.FC<WorkInternExperienceProps> = ({ 
  workExperiences, 
  internships, 
  onUpdate 
}) => {
  const theme = useTheme();
  const [open, setOpen] = useState(false);
  const [experienceType, setExperienceType] = useState<'work' | 'internship'>('work');
  const [editingExp, setEditingExp] = useState<any | null>(null);
  const [formData, setFormData] = useState({
    company: '',
    position: '',
    start_date: '',
    end_date: '',
    period: '',
    description: '',
    type: 'work', // work 或 internship
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<{id: number, type: string} | null>(null);
  const [tabValue, setTabValue] = useState(0); // 0: 全部, 1: 工作经历, 2: 实习经历
  
  // 合并工作和实习经历，创建统一的数据结构
  const allExperiences: Experience[] = [
    ...workExperiences.map(exp => ({
      id: exp.id,
      type: 'work' as const,
      company: exp.company,
      position: exp.position,
      startDate: exp.start_date,
      endDate: exp.end_date || undefined,
      description: exp.description,
      originalData: exp
    })),
    ...internships.map(exp => ({
      id: exp.id,
      type: 'internship' as const,
      company: exp.company,
      position: exp.position,
      startDate: exp.period.split(' 至 ')[0] || exp.period,
      endDate: exp.period.split(' 至 ')[1] || undefined,
      description: exp.description,
      originalData: exp
    }))
  ].sort((a, b) => {
    // 按开始日期降序排序
    try {
      const dateA = new Date(a.startDate).getTime();
      const dateB = new Date(b.startDate).getTime();
      return dateB - dateA;
    } catch {
      return 0;
    }
  });

  const filteredExperiences = tabValue === 0 
    ? allExperiences 
    : allExperiences.filter(exp => 
        (tabValue === 1 && exp.type === 'work') || 
        (tabValue === 2 && exp.type === 'internship')
      );
  
  const resetForm = () => {
    setFormData({
      company: '',
      position: '',
      start_date: '',
      end_date: '',
      period: '',
      description: '',
      type: 'work',
    });
    setEditingExp(null);
    setError('');
  };

  const handleOpenDialog = (exp?: Experience) => {
    if (exp) {
      setEditingExp(exp);
      setExperienceType(exp.type);
      
      if (exp.type === 'work') {
        const workExp = exp.originalData as WorkExp;
        setFormData({
          company: workExp.company,
          position: workExp.position,
          start_date: workExp.start_date.split('T')[0],
          end_date: workExp.end_date ? workExp.end_date.split('T')[0] : '',
          period: '',
          description: workExp.description,
          type: 'work',
        });
      } else {
        const internExp = exp.originalData as InternshipExp;
        setFormData({
          company: internExp.company,
          position: internExp.position,
          start_date: '',
          end_date: '',
          period: internExp.period,
          description: internExp.description || '',
          type: 'internship',
        });
      }
    } else {
      resetForm();
      setExperienceType('work');
    }
    setOpen(true);
  };

  const handleCloseDialog = () => {
    setOpen(false);
    resetForm();
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  const handleSelectChange = (e: any) => {
    const { name, value } = e.target;
    if (name === 'type') {
      setExperienceType(value);
    }
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  const handleSubmit = async () => {
    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      // 根据类型验证表单
      if (formData.type === 'work') {
        if (!formData.company || !formData.position || !formData.start_date) {
          throw new Error('单位名称、职位和开始日期不能为空');
        }

        // 验证日期格式 (YYYY-MM-DD)
        const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
        if (!dateRegex.test(formData.start_date)) {
          throw new Error('开始日期格式无效，请使用YYYY-MM-DD格式');
        }

        if (formData.end_date && !dateRegex.test(formData.end_date)) {
          throw new Error('结束日期格式无效，请使用YYYY-MM-DD格式');
        }
      } else {
        if (!formData.company || !formData.position || !formData.period) {
          throw new Error('单位名称、职位和实习时间段不能为空');
        }
      }

      let url, method, payload;
      
      if (formData.type === 'work') {
        payload = {
          company: formData.company,
          position: formData.position,
          start_date: formData.start_date,
          end_date: formData.end_date || null,
          description: formData.description,
        };
        
        url = editingExp && editingExp.type === 'work' 
          ? `/api/user/work-experience/${editingExp.id}` 
          : '/api/user/work-experience';
          
        method = editingExp && editingExp.type === 'work' ? 'PUT' : 'POST';
      } else {
        payload = {
          company: formData.company,
          position: formData.position,
          period: formData.period,
          description: formData.description,
        };
        
        url = editingExp && editingExp.type === 'internship'
          ? `/api/profile/internships/${editingExp.id}`
          : '/api/profile/internships';
          
        method = editingExp && editingExp.type === 'internship' ? 'PUT' : 'POST';
      }

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '保存经历失败');
      }

      const typeText = formData.type === 'work' ? '工作' : '实习';
      setSuccessMessage(editingExp ? `${typeText}经历更新成功` : `${typeText}经历添加成功`);
      setSuccess(true);
      handleCloseDialog();
      onUpdate(); // 通知父组件更新数据
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (experience: Experience) => {
    setDeletingId({id: experience.id, type: experience.type});
    setDeleteConfirmOpen(true);
  };

  const confirmDelete = async () => {
    if (!deletingId) return;
    
    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      const url = deletingId.type === 'work' 
        ? `/api/user/work-experience/${deletingId.id}` 
        : `/api/profile/internships/${deletingId.id}`;

      const response = await fetch(url, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || '删除经历失败');
      }

      const typeText = deletingId.type === 'work' ? '工作' : '实习';
      setSuccessMessage(`${typeText}经历删除成功`);
      setSuccess(true);
      setDeleteConfirmOpen(false);
      onUpdate(); // 通知父组件更新数据
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
      setDeletingId(null);
    }
  };

  return (
    <Box sx={{ py: 2, px: { xs: 2, md: 3 } }}>
      <Snackbar 
        open={success} 
        autoHideDuration={3000} 
        onClose={() => setSuccess(false)} 
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert 
          severity="success" 
          onClose={() => setSuccess(false)}
          sx={{ 
            borderRadius: '12px',
            boxShadow: '0 8px 16px rgba(0, 0, 0, 0.1)',
            '& .MuiAlert-icon': {
              alignItems: 'center',
            }
          }}
        >
          {successMessage}
        </Alert>
      </Snackbar>

      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography 
          variant="h5" 
          component="h2"
          sx={{ 
            fontSize: '1.5rem',
            fontWeight: 600,
            color: theme.palette.text.primary,
          }}
        >
          工作/实习经历
        </Typography>
        <Button 
          startIcon={<AddIcon />} 
          variant="contained" 
          color="primary"
          onClick={() => handleOpenDialog()}
          sx={{ 
            borderRadius: '8px',
            textTransform: 'none',
            boxShadow: '0 4px 10px rgba(0, 0, 0, 0.07)',
          }}
        >
          添加经历
        </Button>
      </Box>

      {error && (
        <Alert 
          severity="error" 
          sx={{ mb: 3 }}
          onClose={() => setError('')}
        >
          {error}
        </Alert>
      )}

      <Box sx={{ mb: 3 }}>
        <Tabs 
          value={tabValue} 
          onChange={handleTabChange}
          variant="fullWidth"
          sx={{
            mb: 2,
            borderBottom: 1,
            borderColor: 'divider',
            '& .MuiTab-root': {
              textTransform: 'none',
              fontSize: '0.95rem',
              fontWeight: 500,
              minHeight: '48px',
            }
          }}
        >
          <Tab label="全部经历" />
          <Tab label="工作经历" />
          <Tab label="实习经历" />
        </Tabs>
      </Box>

      {filteredExperiences.length === 0 ? (
        <Paper
          elevation={0}
          sx={{
            p: 4,
            textAlign: 'center',
            backgroundColor: alpha(theme.palette.background.paper, 0.7),
            borderRadius: '12px',
            border: `1px dashed ${alpha(theme.palette.divider, 0.5)}`,
          }}
        >
          <Typography color="text.secondary">
            {tabValue === 0 
              ? '暂无工作或实习经历，点击"添加经历"按钮开始添加'
              : tabValue === 1 
                ? '暂无工作经历，点击"添加经历"按钮开始添加'
                : '暂无实习经历，点击"添加经历"按钮开始添加'
            }
          </Typography>
        </Paper>
      ) : (
        <Box sx={{ mt: 2 }}>
          {filteredExperiences.map((exp, index) => (
            <Paper
              key={`${exp.type}-${exp.id}`}
              elevation={0}
              sx={{
                p: 3,
                mb: 3,
                position: 'relative',
                borderRadius: '12px',
                backgroundColor: alpha('#fff', 0.8),
                backdropFilter: 'blur(10px)',
                boxShadow: '0 4px 20px rgba(0, 0, 0, 0.05)',
                border: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
                transition: 'transform 0.2s, box-shadow 0.2s',
                '&:hover': {
                  transform: 'translateY(-2px)',
                  boxShadow: '0 6px 25px rgba(0, 0, 0, 0.1)',
                },
              }}
            >
              <Box sx={{ position: 'absolute', top: 12, right: 12 }}>
                <IconButton
                  size="small"
                  color="primary"
                  onClick={() => handleOpenDialog(exp)}
                  sx={{ mr: 1 }}
                >
                  <EditIcon fontSize="small" />
                </IconButton>
                <IconButton
                  size="small"
                  color="error"
                  onClick={() => handleDelete(exp)}
                >
                  <DeleteIcon fontSize="small" />
                </IconButton>
              </Box>

              <Box sx={{ display: 'flex', alignItems: 'flex-start', mb: 2 }}>
                <Chip 
                  label={exp.type === 'work' ? '工作' : '实习'} 
                  color={exp.type === 'work' ? 'primary' : 'secondary'} 
                  size="small"
                  icon={exp.type === 'work' ? <WorkIcon /> : <BusinessCenterIcon />}
                  sx={{ mr: 2 }}
                />
                <Box>
                  <Typography variant="h6" sx={{ fontWeight: 600, mb: 0.5 }}>
                    {exp.position}
                  </Typography>
                  <Typography color="primary" variant="subtitle1" sx={{ fontWeight: 500, mb: 1 }}>
                    {exp.company}
                  </Typography>
                </Box>
              </Box>

              <Box 
                sx={{ 
                  display: 'flex', 
                  alignItems: 'center', 
                  color: theme.palette.text.secondary,
                  mb: 2
                }}
              >
                <DateRangeIcon fontSize="small" sx={{ mr: 1 }} />
                {exp.type === 'work' ? (
                  <Typography variant="body2">
                    {formatDate(exp.startDate)} - {formatDate(exp.endDate || null)}
                  </Typography>
                ) : (
                  <Typography variant="body2">
                    {(exp.originalData as InternshipExp).period}
                  </Typography>
                )}
              </Box>
              
              {exp.description && (
                <Typography variant="body2" color="text.secondary" sx={{ whiteSpace: 'pre-line' }}>
                  {exp.description}
                </Typography>
              )}
            </Paper>
          ))}
        </Box>
      )}

      {/* 添加/编辑经历对话框 */}
      <Dialog 
        open={open} 
        onClose={handleCloseDialog}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          {editingExp ? (
            experienceType === 'work' ? '编辑工作经历' : '编辑实习经历'
          ) : (
            '添加工作/实习经历'
          )}
        </DialogTitle>
        <DialogContent dividers>
          <Box sx={{ p: 1 }}>
            {error && <Alert severity="error" sx={{ mb: 3 }}>{error}</Alert>}
            
            <Grid container spacing={3}>
              {!editingExp && (
                <Grid item xs={12}>
                  <FormControl component="fieldset">
                    <FormLabel component="legend">经历类型</FormLabel>
                    <RadioGroup 
                      row 
                      name="type" 
                      value={formData.type}
                      onChange={handleSelectChange}
                    >
                      <FormControlLabel 
                        value="work" 
                        control={<Radio />} 
                        label="工作经历" 
                      />
                      <FormControlLabel 
                        value="internship" 
                        control={<Radio />} 
                        label="实习经历" 
                      />
                    </RadioGroup>
                  </FormControl>
                </Grid>
              )}
              
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="单位名称"
                  name="company"
                  value={formData.company}
                  onChange={handleChange}
                  required
                  placeholder="请输入单位名称"
                  variant="outlined"
                />
              </Grid>
              
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="职位"
                  name="position"
                  value={formData.position}
                  onChange={handleChange}
                  required
                  placeholder="请输入职位名称"
                  variant="outlined"
                />
              </Grid>
              
              {experienceType === 'work' ? (
                <>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="开始日期"
                      name="start_date"
                      type="date"
                      value={formData.start_date}
                      onChange={handleChange}
                      required
                      InputLabelProps={{ shrink: true }}
                      variant="outlined"
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="结束日期（留空表示至今）"
                      name="end_date"
                      type="date"
                      value={formData.end_date}
                      onChange={handleChange}
                      InputLabelProps={{ shrink: true }}
                      variant="outlined"
                    />
                  </Grid>
                </>
              ) : (
                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="实习时间段"
                    name="period"
                    value={formData.period}
                    onChange={handleChange}
                    required
                    placeholder="例如：2022-01 至 2022-05"
                    variant="outlined"
                  />
                </Grid>
              )}
              
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="工作/实习描述"
                  name="description"
                  value={formData.description}
                  onChange={handleChange}
                  multiline
                  rows={4}
                  placeholder="描述您的工作/实习内容、职责、成果等"
                  variant="outlined"
                />
              </Grid>
            </Grid>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog} disabled={loading}>
            取消
          </Button>
          <Button 
            onClick={handleSubmit} 
            variant="contained" 
            color="primary"
            disabled={loading}
          >
            {loading ? '保存中...' : '保存'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteConfirmOpen}
        onClose={() => setDeleteConfirmOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>
            确定要删除这条{deletingId?.type === 'work' ? '工作' : '实习'}经历吗？此操作不可撤销。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button 
            onClick={() => setDeleteConfirmOpen(false)} 
            disabled={loading}
          >
            取消
          </Button>
          <Button 
            onClick={confirmDelete} 
            color="error"
            disabled={loading}
          >
            {loading ? '删除中...' : '删除'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default WorkInternExperience; 